package com.example.finalapp;

import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;

import com.parse.Parse;
import com.parse.ParseUser;

public class MyCustomReceiver extends BroadcastReceiver{
	String mSSID_name;
	boolean isEnabled= false;
	WifiManager wifi;

	@Override
	public void onReceive(Context arg0, Intent arg1) {
		Parse.initialize(arg0, "6xDnXjWOcfFRJMlrIJxdVnvtjlTqRgtq8VnSh9Qn", "cxSxdJr5nke0qSxPAIYgU8TwLmzsXZnyzM5U4z8t");
		try 
		{
			JSONObject json = new JSONObject(arg1.getExtras().getString("com.parse.Data"));
			mSSID_name= json.getString("SSID");

			wifi = (WifiManager) arg0.getSystemService(Context.WIFI_SERVICE);

			//--- make sure that wifi is enabled ---//
			if(wifi.isWifiEnabled())
			{
				isEnabled= true;
				wifi.setWifiEnabled(false);
				wifi.setWifiEnabled(true);
			}
			else
				wifi.setWifiEnabled(true);

			//open wifi receiver for checking the strength
			WifiReceiver receiverWifi = new WifiReceiver();
			arg0.registerReceiver(receiverWifi, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));

		} 
		catch (JSONException e) 
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	class WifiReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			List<ScanResult> wifiList = wifi.getScanResults();
			int i=0;
			while(!wifiList.get(i).SSID.equals(mSSID_name) && i < wifiList.size())
			{
				i++;
			}
			if(i != wifiList.size())
			{//our SSID is in range
				ParseUser user = ParseUser.getCurrentUser();
				if(Integer.valueOf(wifiList.get(i).level) > -83)
					user.put("IsHome", true);
				else
					user.put("IsHome", false);
			}
		}

	}

}
